package com.wangtianxiang.sql.generator.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

    private FileUtils() {}

    public static List<File> listFile(String path) {
        return listFile(new File(path), new ArrayList<File>(), null);
    }

    public static List<File> listFile(String path,String fileExt){
        return listFile(new File(path),new ArrayList<File>(),fileExt);
    }

    public static boolean writeFile(String content,String filename){
        return writeFile(content,filename, StandardCharsets.UTF_8.name(),false);
    }


    public static boolean writeFile(String content,String filename,boolean append){
       return writeFile(content,filename, StandardCharsets.UTF_8.name(),append);
    }

    public static boolean writeFile(String content,String filename,String charset,boolean append){
        File file = new File(filename);
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,append),charset));
            writer.write(content);
            writer.flush();
            writer.close();
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 文件夹或文件是否存在
     * @param filename
     * @return
     */
    public static boolean exitsFile(String filename){
        boolean result = false;
        try {
            File file = new File(filename);
            result = file.exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取文件拓展名
     * @param file
     * @return
     */
    public static String getFileExt(File file){
        return file.getName().substring(file.getName().lastIndexOf(".") + 1);
    }

    private static List<File> listFile(File dir,List<File> fileList,String fileExt){
        File[] files = dir.listFiles();
        if(files == null){
            throw new RuntimeException(String.format("files is null,dir: %s",dir));
        }
        for(File file : dir.listFiles()){
            if(!file.isDirectory()){
                if(fileExt == null || fileExt != null && fileExt.equalsIgnoreCase(getFileExt(file))){
                    fileList.add(file);
                }
            }else{
                listFile(file,fileList,fileExt);
            }
        }
        return fileList;
    }


}
